package org.KeyCrafter.server;

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicIntegerArray;

public class BackgroundServerImpl implements BackgroundServer{
    private ThreadPoolExecutor threadPool;
    // 保证自增和自减操作的原子性
    private AtomicIntegerArray pending;

    public void init(){
        threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(KeyCrafter_BS_NUM_OPS);
        pending = new AtomicIntegerArray(KeyCrafter_BS_NUM_OPS);
    }

    public BackgroundServerImpl() {
        init();
    }

    // 使用FutureTask异步实现伪服务器的阻塞队列
    @Override
    public void createBackgroundJob(int type, Object arg) {
       threadPool.execute(() -> processBackgroundJobs(type,arg));
       pending.getAndDecrement(type);
    }

    @Override
    public int pendingJobsOfType(int type) {
        return pending.get(type);
    }

    private void processBackgroundJobs(int type, Object arg) {
        if (type == KeyCrafter_BS_AOF_FSYNC) {
            FileChannel channel = (FileChannel) arg;
            try {
                channel.force(false);
                pending.getAndIncrement(type); // 任务完成时阻塞数减一
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
